import { APICartList, APICartUp, APIDelete} from '..//fetch.js';
import { getCookie } from '../tools.js';

$('#head').load('../dewu/head.html');
$('#foot').load('../dewu/foot.html');

layui.use(['layer'], function () {
    var layer = layui.layer;

    var username = getCookie('login_user');

    APICartList({
        username
    }).then(({ data }) => {

        var html = '';
        $.each(data, (index, { id, img, gname, price, count }) => {
            console.log(data);
            html += `
            <tr data-id = ${id}>
            <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
            <td class="goods"><img src="${img}" alt="" /><span>${gname}</span></td>
            <td class="price">${price}</td>
            <td class="count"><span class="reduce">${count > 1 ? '-' : ''}</span>
                <input class="count-input" type="text" value="${count}" />
                <span class="add">+</span></td>
            <td class="subtotal">${(price * count).toFixed(2)}</td>
            <td class="operation"><span class="delete">删除</span></td>
        </tr>
            `
        })
        $('#list').html(html)
    })
    var timer = null;
    // 加法
    $(document).on('click', '.add', function () {
        // var parent = $(self).parents('tr');

        var id = $(this).parents('tr').attr('data-id');
        var count = $(this).parents('tr').find('.count-input').val();

        count++;
        var price = $(this).parents('tr').find('.price').text();
        $(this).parents('tr').find('.subtotal').text((count * price).toFixed(2));
        clearTimeout(timer);

        timer = setTimeout(() => {
            APICartUp({
                id,
                count
            }).then(({ code }) => {
                if (code) {
                    $(this).parents('tr').find('.count-input').val(count);
                }
            });
        }, 300)

        $(this).parents('tr').find('.reduce').text('-');
    })
    // 减法
    $(document).on('click', '.reduce', function () {
        // var parent = $(self).parents('tr');
        var id = $(this).parents('tr').attr('data-id');
        var count = $(this).parents('tr').find('.count-input').val();

        count--
        if (count <= 1) {
            $(this).parents('tr').find('.reduce').text('')
        }
        var price = $(this).parents('tr').find('.price').text();
        $(this).parents('tr').find('.subtotal').text((count * price).toFixed(2))
        clearTimeout(timer);

        timer = setTimeout(() => {
            APICartUp({
                id,
                count
            }).then(({ code }) => {
                if (code) {
                    $(this).parents('tr').find('.count-input').val(count);
                }
            });
        }, 300)
    })

})
// 全选
$('.check-all').change(function () {
    $('.check-one').prop('checked', $(this).prop('checked'))
    getTotal()
})
// 单选
$(document).on('click', '.check-one', function () {
    checkAll();

})
function checkAll() {
    if ($('.check-one').length === $('.check-one:checked').length) {
        $('.check-all').prop('checked', true)
    } else {
        $('.check-all').prop('checked', false)
    }
    getTotal()
}
// 删除
$(document).on('click', '#list .delete', function () {
    APIDelete({
        ids: JSON.stringify([$(this).parents('tr').attr('data-id')])
    }).then(({ code, msg }) => {
        if (code) {
            $(this).parents('tr').remove();
            checkAll();
            layer.msg('删除成功')
        } else {
            layer.msg(msg)
        }
    })
})

// 删除全部
$('#deleteAll').click(function () {
    var ids = [];

    $.each($('.check-one:checked'), function (index, item) {
        ids.push($(item).parents('tr').attr('data-id'))
    })
    APIDelete({
        ids: JSON.stringify(ids)
    }).then(({ code, msg }) => {
        if (code) {
            $('.check-one:checked').parents('tr').remove();
            checkAll();
            layer.msg('删除成功')
        } else {
            layer.msg(msg)
        }
    })
})
//合计
function getTotal() {
    var count = 0;
    var total = 0;
    $.each($('.check-one:checked'), function (_, item) {
      count += $(this).parents('tr').find('.count-input').val() * 1
      total += $(this).parents('tr').find('.subtotal').text() * 1
    });
  
    $('#selectedTotal').text(count);
  
  
  
    $('#priceTotal').text(total);
  }